using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace ObjectModel
{
    [Serializable]
    public abstract class ItemBaseCollection : IEnumerable
    {
        #region fields
        protected IList coll = null;
        #endregion

        #region ctor
        protected ItemBaseCollection() : this(new ArrayList())
        { 
        }
        protected ItemBaseCollection(IList list)
        {
            coll = list;
        }
        #endregion

        #region properties
        public virtual int Count
        {
            get { return coll.Count; }
        }
        public virtual ItemBase this[int index]
        {
            get
            {
                return coll[index] as ItemBase;
            }
        }
        public abstract Type ItemType
        {
            get;
        }
        #endregion

        #region methods
        protected virtual int LoadById(Type clazz, int id)
        {
            ItemBase entity = GetItemById(id);
            if (entity != null) return IndexOf(entity);

            ItemBase itemLoaded = Proxy.Current.GetItemById(clazz, id);

#if PROFILEDATA
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            using (System.IO.Stream stream = new System.IO.MemoryStream())
            {
                formatter.Serialize(stream, itemLoaded);

                Console.WriteLine(string.Format("Stream size (Clazz:{0}, id:{1}): {2} ", clazz.ToString(), id, stream.Length));
            }
#endif
            if (itemLoaded == null) return -1;

            return coll.Add(itemLoaded);
        }

        public virtual int IndexOf(object item)
        {
            if (item == null) return -1;
            for (int i = 0; i < coll.Count; i++)
            {
                ItemBase itm = (ItemBase)coll[i];
                if (itm.Id == ((ItemBase)item).Id)
                    return i;
            }
            return -1;
        }

        protected virtual ItemBase GetItemById(int Id)
        {
            int pos = -1;
            foreach (ItemBase obj in this.coll)
            {
                if (obj.Id == Id)
                {
                    pos = coll.IndexOf(obj);
                    break;
                }
            }
            if (pos >= 0) return coll[pos] as ItemBase;
            return default(ItemBase);
        }
        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return coll.GetEnumerator();
        }

        #endregion
    }
}
